import numpy as np
import matplotlib.pyplot as mp
import load_foil as lf
import cubic_interpo_splint as ci
import integral as sl
from matplotlib import pyplot as plt
from matplotlib import cm



def plot_airflows_curves():
	"Fonction tracant les courbe d'ecoulement de l'air"
	(ex,ey,ix,iy) = lf.load_foil("naca747a315.dat")
	e_spline_value = ci.spline(ex, ey)
	i_spline_value = ci.spline(ix, iy)
	h_max = np.amax(ey)
	h_min = np.amin(iy)

	for lbda in np.arange(0, 1, 0.05):
		for i in range(0, len(ex) - 1):
	   		mp.plot(np.arange(ex[i], ex[i+1], 0.0001), (1-lbda)*e_spline_value[i][0](np.arange(ex[i], ex[i+1], 0.0001)) + 3*lbda*h_max, 'k')

	for lbda in np.arange(0, 1, 0.05):
		for i in range(0, len(ix) - 1):
	   		mp.plot(np.arange(ix[i], ix[i+1], 0.0001), (1-lbda)*i_spline_value[i][0](np.arange(ix[i], ix[i+1], 0.0001)) + 3*lbda*h_min, 'k')

	mp.ylabel('y')
	mp.xlabel('x')
	mp.show()
	mp.clf()

def spline_derivative(coeff, lbda):
	"Fonction retournant la derivee d'un polynome de degres 3"
	return lambda x: (3*coeff[0]*(x**2) + 2*coeff[1]*x + coeff[2])*(1-lbda)


def pressures_value(spline_line, x, lbda, t, rho):
	"Fonction determinant les pression pour une courbe d'ecoulement d'aire donnee par lambda"
	s_length = 0
	for i in range(0, len(spline_line)):
		s_length += sl.splineLength(spline_derivative(spline_line[i][1], lbda), x[i], x[i+1], sl.integral_rec_up)
	return (s_length*rho)/t


def geti_from_x(x, T):
	i = 0
	while (x > T[i]):
		i+=1
	return min(i, len(T)-2)



def plot_airflows_pressures():
	"Fonction tracant la carte des pressions"
	size_plot = 60

	(ex,ey,ix,iy) = lf.load_foil("naca747a315.dat")
	e_spline_value = ci.spline(ex, ey)
	i_spline_value = ci.spline(ix, iy)
	h_max = np.amax(ey)
	h_min = np.amin(iy)

	step_x = 1/float(size_plot)
	step_y = 0.5/float(size_plot)
	step_lambda = 0.1

	min_pressure = pressures_value(i_spline_value, ix, 1, 1, 1.293)
	pressures = T = [[0 for i in range (0, size_plot)] for i in range (0, size_plot)]
	
	middle = 2 * size_plot / 5
	for y in range (0, size_plot - middle):
		for x in range (0, size_plot):
			lbda = 0
			i = geti_from_x(x*step_x, ex)
			while (y*step_y > ((1-lbda)*e_spline_value[i][0](x*step_x) + 3*lbda*h_max) and lbda < 0.9):
				lbda+=step_lambda
			press = pressures_value(e_spline_value, ex, lbda, 1, 1.293)
			if(press <=min_pressure):
				press =  min_pressure
			T[y + middle][x] =  press

	for y in range (-middle, 0):
		for x in range (0, size_plot):
			lbda = 0
			i = geti_from_x(x*step_x, ex)
			while (y*step_y < ((1-lbda)*i_spline_value[i][0](x*step_x) + 3*lbda*h_min) and lbda < 0.9):
				lbda+=step_lambda
			press = pressures_value(i_spline_value, ix, lbda, 1, 1.293)
			if(press <=min_pressure):
				press =  min_pressure
			T[y + middle][x] =  press

	mp.imshow(T,cmap=cm.hot)
	ax = mp.gca()
	ax.invert_yaxis()
	# mp.savefig("courbes_de_pressions")
	mp.show()



if __name__ == "__main__":
	plot_airflows_curves()
	plot_airflows_pressures()

